﻿using Newtonsoft.Json.Linq;
using SmartPatientCentre.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
using Windows.UI.Popups;

namespace SmartPatientCentre.Common
{
    public class DownloadClient
    {
        public HttpClient client;

        // Default constructor
        public DownloadClient()
        {
            client = new HttpClient();

            // set default URI
            client.BaseAddress = new Uri("http://hospitaldbsecure.azurewebsites.net/");

            //// Testing Uri
            //client.BaseAddress = new Uri("http://localhost:52762/");

            // set JSON as default header
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
        }

        // Method to authenticate user
        public async Task<User> AuthenticateUser(string username, string password)
        {
            client.DefaultRequestHeaders.Clear();

            // Add Content-Type Header
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/x-www-form-urlencoded"));

            // Construct Http content
            string usernamePassword = string.Format("grant_type=password&username={0}&password={1}", username, password);
            StringContent content = new StringContent(usernamePassword);

            // Post Async and get response message
            //Uri tokenUri = new Uri("http://hospitaldbsecure.azurewebsites.net/Token");
            HttpResponseMessage response = await client.PostAsync("Token", content);

            if(response.IsSuccessStatusCode)
            {
                // Deserialize JSON to User object
                return await response.Content.ReadAsAsync<User>();
            }
            else
            {
                Error error = await response.Content.ReadAsAsync<Error>();
                throw new HttpRequestException(error.Description);
            }
        }

        // Method to get All Patients from Database
        public async Task<List<Patient>> GetPatients(User user)
        {
            // Query string to get all patients
            string query = "api/Patient";

            // Create Authorization header
            string schemeToken = user.TokenType + " " + user.AccessToken;

            // Add header to request message
            client.DefaultRequestHeaders.Add("Authorization", schemeToken);

            // Send GET request
            HttpResponseMessage response = await client.GetAsync(query);

            // Check if response message is a success
            if (response.IsSuccessStatusCode)
            {
                var patients = await response.Content.ReadAsAsync<List<Patient>>();
                return patients;
            }
            else
            {
                string message = string.Format("Error {0} : {1}", response.StatusCode, response.ReasonPhrase);
                throw new HttpRequestException(message);
            }

        }

        // Get Patients by User
        public async Task<List<Patient>> GetPatientsByUser(User user)
        {
            // Query string to get all patients
            string query = "api/Patient/List";

            // Create Authorization header
            string schemeToken = user.TokenType + " " + user.AccessToken;

            // Add header to request message
            client.DefaultRequestHeaders.Add("Authorization", schemeToken);

            // Send GET request
            HttpResponseMessage response = await client.GetAsync(query);

            // Check if response message is a success
            if (response.IsSuccessStatusCode)
            {
                var patients = await response.Content.ReadAsAsync<List<Patient>>();
                return patients;
            }
            else
            {
                string message = string.Format("Error {0} : {1}", response.StatusCode, response.ReasonPhrase);
                throw new HttpRequestException(message);
            }
        }

        // Get Data instance from Web API
        public async Task<Data> GetDataByUser(User user)
        {
            // Query string to get all patients
            string query = "api/Patient/List";

            // Create Authorization header
            string schemeToken = user.TokenType + " " + user.AccessToken;

            // Add header to request message
            client.DefaultRequestHeaders.Add("Authorization", schemeToken);

            // Send GET request
            HttpResponseMessage response = await client.GetAsync(query);

            // Check if response message is a success
            if (response.IsSuccessStatusCode)
            {
                var data = await response.Content.ReadAsAsync<Data>();
                return data;
            }
            else
            {
                string message = string.Format("Error {0} : {1}", response.StatusCode, response.ReasonPhrase);
                throw new HttpRequestException(message);
            }
        }

        //public async Task<List<Patient>> GetPatientsOpen()
        //{
        //    Uri openDb = new Uri("http://hospitaldbopen.azurewebsites.net/api/Patient");
        //    HttpResponseMessage response = await client.GetAsync(openDb);

        //    // Check if response message is a success
        //    if (response.IsSuccessStatusCode)
        //    {
        //        var patients = await response.Content.ReadAsAsync<List<Patient>>();
        //        return patients;
        //    }
        //    else
        //    {
        //        string message = string.Format("Error {0} : {1}", response.StatusCode, response.ReasonPhrase);
        //        throw new HttpRequestException(message);
        //    }
        //}
    }
}
